package com.example.topguli;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriterLockTest {
    public static void main(String[] args) {
        Cache cache = new Cache();
        for (Integer i = 0; i < 30; i++) {
            Integer temp=i;
            new Thread(()->{
                cache.setData(temp.toString(),temp);
            }).start();
        }

        for (Integer i = 0; i < 30; i++) {
            Integer temp=i;
            new Thread(()->{
                cache.getData(temp.toString());
            }).start();
        }
    }
}
class Cache{
    private volatile Map<String,Object> map=new HashMap<>();
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    public void setData(String name,Integer id){
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"准备写入数据");
            map.put(id.toString(),name);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"写入数据完成");
            writeLock.unlock();
        }
    }
    public String getData(String id){
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"准备读取数据");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("数据为"+map.get(id.toString()));
            readLock.unlock();
            return(String)map.get(id.toString());
        }
    }
}